package org.whuims.core.dataprocessor.page;

import java.util.List;

/**
 * Created by cheng on 2016/12/29.
 */
public class PageTypeDetector {

    private List<PageUnit> pageUnits;

    public PageTypeDetector(List<PageUnit> pageUnits) {
        this.pageUnits = pageUnits;
    }

    public void detect() {
        detectLastPage();
        findMainPart();
    }

    private void findMainPart() {
        boolean mainPartPageMatch = false;
        for (int i = 0; i < pageUnits.size(); i++) {
            PageUnit pu = pageUnits.get(i);
            if (pu.getType() != null && pu.getType().trim().length() > 0) {
                continue;
            }
            //System.out.println("分析类型"+i);
            if (isMainPart(pu)) {
                mainPartPageMatch = true;
            }
            if (!mainPartPageMatch) {
                pu.setType(PageUnit.PAGE_HEAD);
            } else {
                pu.setType(PageUnit.PAGE_MAIN_PART);
            }
        }
        for (int i = 0; i < pageUnits.size(); i++) {
            PageUnit pu = pageUnits.get(i);
            if (pu.getType().equals(PageUnit.PAGE_HEAD)) {
                if (matchsIndexPage(pu)) {
                    pu.setType(PageUnit.PAGE_INDEX);
                }
            }
        }
    }

    private boolean matchsIndexPage(PageUnit pu) {
        for (String line : pu.getLines()) {
            if (line.contains(".........")) {
                return true;
            }
            String l = line.trim().replaceAll("\\s+", "");
            if (l.contains("目次") || l.contains("目录")) {
                l = l.replaceAll("[^\\w\\s]+", "");
                if (l.equals("目次") || l.equals("目录")) {
                    line = l.replaceAll("[^\\w\\s]+", "");
                    return true;
                }
            }
        }
        return false;
    }

    private boolean isMainPart(PageUnit pu) {
        List<String> lines = pu.getLines();
        for (String line : lines) {
            if (line.contains("围") || line.contains("总")) {
                //System.out.println("当前文本："+line);
                if (line.trim().replaceAll("\\s+", "").equals("1范围") || line.replaceAll("\\s+", "").startsWith("1适用范围") || line.matches("\\s*1\\s*总\\s*则") || line.equals("1主题内容与适用范围") || line.matches("[第1一章编总则范围主题]+")) {
                    //System.out.println("是开头部分");
                    return true;
                }
            }
        }
        return false;
    }

    private void detectLastPage() {
        PageUnit pu = pageUnits.get(pageUnits.size() - 1);
        for (String l : pu.getLines()) {
            String line = l.trim();
            if (line.contains("出版社出版") || (line.endsWith("必究") && line.contains("版权"))) {
                pu.setType(PageUnit.PAGE_COPYRIGHT);
                break;
            }
        }
        pu.setType(PageUnit.PAGE_COPYRIGHT);
    }
}
